package org.dtrd.modules.achievement.controller;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.CheckUtil;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.achievement.entity.bean.PatientSigninRecord;
import org.dtrd.modules.achievement.entity.bean.SignInAction;
import org.dtrd.modules.achievement.entity.bean.SigninRecord;
import org.dtrd.modules.achievement.service.IDtrdEntRdSigninRecordService;
import org.dtrd.modules.record.entity.bean.CheckinRecord;
import org.dtrd.modules.record.service.*;
import org.dtrd.modules.suggest.entity.bean.SigninRecordSuggestListInfo;
import org.dtrd.modules.suggest.service.IDtrdEntRdSigninRecordSuggestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author 萧
 * @date:2021-10-22 10:45 上午
 **/
@RestController
@Slf4j
@Api(tags = "107健管服务")
@RequestMapping("/107")
public class HealthManageController extends BaseController {


    @Autowired
    private IDtrdEntRdSigninRecordService signinRecordService;

    @Autowired
    private ISugarRecordService sugarRecordService;

    @Autowired
    private IBloodPressureRecordService bloodPressureRecordService;

    @Autowired
    private IFoodRecordService foodRecordService;

    @Autowired
    private IHeightWeightRecordService heightWeightRecordService;

    @Autowired
    private IInsulinRecordService insulinRecordService;

    @Autowired
    private IKetoneRecordService ketoneRecordService;

    @Autowired
    private IMedicalRecordService medicalRecordService;

    @Autowired
    private ISportRecordService sportRecordService;

    @Autowired
    private IWaistlineRecordService waistlineRecordService;

    @Autowired
    private INutrientRecordService nutrientRecordService;

    @Autowired
    private IDtrdEntRdSigninRecordSuggestService signinRecordSuggestService;

    /**
     * 按照日期查询打卡记录，默认查询当天记录
     *
     * @param request
     * @return
     */
    @ApiOperation("查询今日打卡记录")
    @PostMapping("/01/1070106")
    public Result<?> getDailySigninRecords(@RequestBody SigninRecord request) {
        log.info("HealthManageController.getDailySigninRecords.[request]" + request);
        if (isIntParamInvalid(request.getPatientId())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        String date = request.getRecordDate();
        if (CheckUtil.isEmpty(date)) {
            date = DateUtils.formatDate();
        }
        SigninRecord sr = signinRecordService.getSigninRecordByPatientIdAndDate(request.getPatientId(), date);
        if (sr != null && CheckUtil.isNotEmpty(sr.getSignInActionList())) {
            List<SignInAction> actionList = sr.getSignInActionList();
            List<PatientSigninRecord> dataList = new ArrayList<>(actionList.size());
            actionList.stream()
                    // 过滤未配置项
                    .filter(action -> !(StringUtils.isEmpty(action.getStarttime()) || StringUtils.isEmpty(action.getEndtime())))
                    // 过滤待打卡项
                    .filter(action -> action.getIsDone() != Constant.RecordState.TO_BE_RECORD.getState())
                    .map(action -> {
                        PatientSigninRecord record = new PatientSigninRecord();
                        record.setState(action.getIsDone());
                        record.setRecordType(action.getRecordType());
                        record.setDataId(action.getDataId());
                        Constant.RecordType recordType = Constant.RecordType.valueOf(action.getRecordType());
                        if (recordType != null) {
                            record.setTitle(recordType.getName());
                            if (recordType == Constant.RecordType.SUGAR) {
                                record.setIcon(recordType.getIcon() + action.getSubType() + ".png");
                            } else {
                                record.setIcon(recordType.getIcon());
                            }
                            //
                            record.setSubType(action.getSubType());
                            // 查询对应健康记录
                            if (record.getDataId() > 0) {
                                // 查询记录详情
                                switch (recordType) {
                                    case SUGAR:
                                        CheckinRecord sugarCheckinRecord = sugarRecordService.selectRecordById(action.getDataId());
                                        if (sugarCheckinRecord != null) {
                                            record.setValue(sugarCheckinRecord.getSugarValue() + "");
                                            record.setRecordTime(sugarCheckinRecord.getRecordTimeHm());
                                            record.setImgList(sugarCheckinRecord.getImages());
                                        }
                                        break;
                                    case BLOOD_PRESSURE:
                                        CheckinRecord bpCheckinRecord = bloodPressureRecordService.selectRecordById(action.getDataId());
                                        if (bpCheckinRecord != null) {
                                            record.setRecordTime(bpCheckinRecord.getRecordTimeHm());
                                            record.setImgList(bpCheckinRecord.getImages());
                                            record.setValue(bpCheckinRecord.getHighPressure() + "/" + bpCheckinRecord.getLowPressure());
                                        }
                                        break;
                                    case SPORT:
                                        CheckinRecord sportCheckinRecord = sportRecordService.selectRecordById(action.getDataId());
                                        if (sportCheckinRecord != null) {
                                            record.setRecordTime(sportCheckinRecord.getRecordTimeHm());
                                            record.setImgList(sportCheckinRecord.getImages());
                                        }
                                        break;
                                    case MEDICAL:
                                        CheckinRecord medicalCheckinRecord = medicalRecordService.selectRecordById(action.getDataId());
                                        if (medicalCheckinRecord != null) {
                                            record.setRecordTime(medicalCheckinRecord.getRecordTimeHm());
                                            record.setImgList(medicalCheckinRecord.getImages());
                                        }
                                        break;
                                    case DIET:
                                        CheckinRecord dietCheckinRecord = foodRecordService.selectRecordById(action.getDataId());
                                        if (dietCheckinRecord != null) {
                                            List<SigninRecordSuggestListInfo> signinRecordSuggestListInfo = signinRecordSuggestService.getSigninRecordSuggestListById(dietCheckinRecord.getDataId());
                                            if (signinRecordSuggestListInfo != null) {
                                                final int[] totalScore = new int[1];
                                                signinRecordSuggestListInfo.forEach(l -> {
                                                    String[] scores = l.getScore().split(",");
                                                    int sumScore = 0;
                                                    for (String score : scores) {
                                                        sumScore = sumScore + Integer.parseInt(score);
                                                    }
                                                    totalScore[0] = totalScore[0] + sumScore;
                                                });
                                                int sum = Arrays.stream(totalScore).sum();
                                                long count = signinRecordSuggestListInfo.stream().count();
                                                log.info(sum + "====" + count);
                                                float score = count !=0?(float) (sum / count):0;
                                                record.setScore(score);
                                            }
                                            record.setSigninRecordSuggestListInfo(CollectionUtil.isEmpty(signinRecordSuggestListInfo)?null:signinRecordSuggestListInfo);
                                            record.setRecordTime(dietCheckinRecord.getRecordTimeHm());
                                            record.setDesc(dietCheckinRecord.getFoodRecordDesc());
                                            record.setImgList(dietCheckinRecord.getImages());
                                        }
                                        break;
                                    case WEIGHT:
                                        CheckinRecord weightCheckinRecord = heightWeightRecordService.selectRecordById(action.getDataId());
                                        if (weightCheckinRecord != null) {
                                            record.setRecordTime(weightCheckinRecord.getRecordTimeHm());
                                            record.setValue(weightCheckinRecord.getWeight() + "");
                                            record.setImgList(weightCheckinRecord.getImages());
                                        }
                                        break;
                                    case WAIST:
                                        CheckinRecord waistCheckinRecord = waistlineRecordService.selectRecordById(action.getDataId());
                                        if (waistCheckinRecord != null) {
                                            record.setRecordTime(waistCheckinRecord.getRecordTimeHm());
                                            record.setValue(waistCheckinRecord.getWaist() + "");
                                            record.setImgList(waistCheckinRecord.getImages());
                                        }
                                        break;
                                    case KETONE:
                                        CheckinRecord ketongCheckinRecord = ketoneRecordService.selectRecordById(action.getDataId());
                                        if (ketongCheckinRecord != null) {
                                            record.setRecordTime(ketongCheckinRecord.getRecordTimeHm());
                                            record.setValue(ketongCheckinRecord.getKetone() + "");
                                            record.setImgList(ketongCheckinRecord.getImages());
                                        }
                                        break;
                                    case INSULIN:
                                        CheckinRecord insulinCheckinRecord = insulinRecordService.selectRecordById(action.getDataId());
                                        if (insulinCheckinRecord != null) {
                                            record.setRecordTime(insulinCheckinRecord.getRecordTimeHm());
                                            record.setImgList(insulinCheckinRecord.getImages());
                                        }
                                        break;
                                    case SLEEP:
//                                    Record sportRecord = sportRecordService.selectRecordById(action.getDataId());
                                        break;
                                    case NUTRIENT:
                                        CheckinRecord nutrientCheckinRecord = nutrientRecordService.selectRecordById(action.getDataId());
                                        if (nutrientCheckinRecord != null) {
                                            record.setRecordTime(nutrientCheckinRecord.getRecordTimeHm());
                                            record.setDesc(nutrientCheckinRecord.getNutrientDesc());
                                            record.setImgList(nutrientCheckinRecord.getImages());
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                        if (CheckUtil.isEmpty(record.getRecordTime())) {
                            record.setRecordTime(String.format("%s-%s", action.getStarttime(), action.getEndtime()));
                        }
                        //针对血糖 、饮食 赋值子类型
                        Integer subType = action.getSubType();
                        if (subType != null) {
                            switch (recordType) {
                                case SUGAR:
                                    record.setRecordTypeName(Optional.ofNullable(Constant.SugarRecordType.valueOf(subType)).map(Constant.SugarRecordType::getName).orElse(""));
                                    break;
                                case DIET:
                                    record.setRecordTypeName(Optional.ofNullable(Constant.FoodRecordType.valueOf(subType)).map(Constant.FoodRecordType::getName).orElse(""));
                                    break;
                                case INSULIN:
                                    record.setRecordTypeName(Optional.ofNullable(Constant.InsulinRecordType.valueOf(subType)).map(t -> t.getName()).orElse(""));
                                    break;
                                case MEDICAL:
                                    record.setRecordTypeName(Optional.ofNullable(Constant.MedicalRecordType.valueOf(subType)).map(t -> t.getName()).orElse(""));
                                    break;
                                case BLOOD_PRESSURE:
                                    record.setRecordTypeName(Optional.ofNullable(Constant.BloodPressureRecordType.valueOf(subType)).map(t -> t.getName()).orElse(""));
                                    break;
                                case NUTRIENT:
                                    record.setRecordTypeName(Optional.ofNullable(Constant.NutrientRecordType.valueOf(subType)).map(t -> t.getName()).orElse(""));
                                    break;
                                default:
                                    break;
                            }
                        }
                        record.setTitle(record.getRecordTypeName() + record.getTitle());
                        record.setDataId(action.getDataId());
                        return record;
                    }).sorted(Comparator.comparingInt(PatientSigninRecord::getState).thenComparing((o1, o2) -> o2.getRecordTime().compareTo(o1.getRecordTime()))).forEach(dataList::add);

            return Result.OK(dataList);
        }
        Result<List> ok = Result.OK(Collections.EMPTY_LIST);
        ok.setMessage("这一天没有打卡记录哦");
        return ok;
//        return error(SystemState.ResponseState.STATE_NO_RECORD);
    }

}
